<template>
  <div class="set_budget">
    <header-go-back title="预算管理" @back="handleGoBack">
    <template v-slot:text>
      <div @click="showMonth = true" class="show_month">{{ getFormatMonth(currentDate) }}</div>
      <van-datetime-picker
        class="select_month"
        v-model="currentDate"
        v-if="showMonth"
        type="year-month"
        :formatter="formatter"
        @cancel="showMonth = false"
        @confirm="selectMonth"
      />
    </template>
    </header-go-back>
    <div class="budget_content">
      <div class="budget_card">
        <div class="card_surplus">
          <van-circle
            v-model:current-rate="currentRate"
            :rate="getCircleRate()"
            :speed="100"
            size="60px"
            color="#fff"
            layer-color="#FFE4E1"
            stroke-width="120"
          />
          <div class="card_text">
            <div class="card_title">剩余预算</div>
            <div class="card_number">{{ (totalBudget - totalPay).toFixed(2) }}</div>
          </div>
        </div>
        <div class="card_compute">
          <div class="card_text" @click="handleOpenBudget">
            <div class="card_title">
              总预算
              <i class="iconfont icon-icon1"></i>
            </div>
            <div class="card_number">{{ totalBudget.toFixed(2) }}</div>
          </div>
          <div class="card_text">
            <div class="card_title">日均消费</div>
            <div class="card_number">{{ (totalPay/new Date().getDate()).toFixed(2) }}</div>
          </div>
          <div class="card_text">
            <div class="card_title">剩余日预算</div>
            <div class="card_number">{{ getMoreBudget().toFixed(2) }}</div>
          </div>
        </div>
      </div>
    </div>
    <van-action-sheet v-model:show="actionVisible">
      <div class="budget_input">
        <div class="input_header">
          <div class="header_title">预算金额</div>
          <div class="header_save" @click="handleConfirmBudget">√</div>
        </div>
        <div class="input">
          <input type="number" placeholder="请输入预算金额" v-model="budget">
          <i class="iconfont icon-shanchu delete" @click="handleBackspaceBudget"></i>
        </div>
      </div>
    </van-action-sheet>
  </div>
</template>


<script lang="ts">
import { computed, defineComponent, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import HeaderGoBack from '@/components/common/HeaderGoBack.vue'
import { getBudget, setBudget } from '@/api/budget'
import dayjs from 'dayjs'
import { useStore } from 'vuex'
import { getSumRange } from '@/api/bill'
import { getMonthCount, getStartAndEnd } from '@/utils/helper'
export default defineComponent({
  components: {
    HeaderGoBack
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const currentRate = ref(0)
    const actionVisible = ref(false)
    const budget = ref(0.00)
    const showMonth = ref(false)
    const currentDate = ref(new Date())
    const bookId = computed(() => store.state.book.id)
    const getCircleRate = () => {
      const rate = ((totalBudget.value - totalPay.value)/totalBudget.value)*100
      currentRate.value = rate
      return rate
    }
    const totalBudget = ref(0)
    const totalPay = ref(0)
    // 返回首页
    const handleGoBack = () => {
      router.push('/')
    }
    // 确认预算
    const handleConfirmBudget = () => {
      actionVisible.value = false
      handleSetBudget()
      handleGetBudget()
    }
    // 设置预算
    const handleSetBudget = () => {
      setBudget({
        bookId: bookId.value,
        date: dayjs(currentDate.value as Date).format("YYYY-MM"),
        budget: budget.value
      }).then((res) => {
        console.log(res, '106');
      })
    }
    // 获取预算
    const handleGetBudget = () => {
      getBudget({
        date: dayjs(currentDate.value as Date).format("YYYY-MM"),
        id: bookId.value
      }).then((res) => {
        if(typeof res.code === 'number' && res.code === 100) {
          totalBudget.value = res.data ? res.data.budget : 0
        }
      })
    }
    // 重置预算
    const handleBackspaceBudget = () => {
      budget.value = 0.00
    }
    // 日历展示格式化
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const formatter = (type: string, val: any) => {
      if (type === 'year') {
        return `${val}年`;
      }
      if (type === 'month') {
        return `${val}月`;
      }
      return val;
    };
    // 获取月份的格式化形式
    const getFormatMonth = (value: Date) => {
      return dayjs(value).format('YYYY年M月')
    }
    // 选择月份
    const selectMonth = () => {
      showMonth.value = false
      handleGetBudget()
      handleGetTotalPay()
    }
    // 获取当月总支出金额
    const handleGetTotalPay = () => {
      const { start, end } = getStartAndEnd(new Date)
      getSumRange({
        id: bookId.value, 
        start,
        end,
        type: 'pay'
      }).then((res) => {
        if(typeof res.code === 'number' && res.code === 100) {
          totalPay.value = res.data ? res.data : 0
        }
      })
    }
    // 获取剩余日预算
    const getMoreBudget = () => {
      const count = getMonthCount(new Date().getMonth(), new Date().getFullYear()) as number
      const sum = Number(((totalBudget.value - totalPay.value)/(count - new Date().getDate())).toFixed(2))
      return sum > 0 ? sum : 0
    }
    // 打开设置预算弹窗
    const handleOpenBudget = () => {
      budget.value = totalBudget.value
      actionVisible.value = true
    }
    onMounted(() => {
      handleGetBudget()
      handleGetTotalPay()
    })
    return {
      currentRate,
      actionVisible,
      budget,
      showMonth,
      currentDate,
      totalBudget,
      totalPay,
      getCircleRate,
      handleGoBack,
      handleConfirmBudget,
      handleBackspaceBudget,
      formatter,
      getFormatMonth,
      selectMonth,
      getMoreBudget,
      handleOpenBudget
    }
  }
})
</script>

<style scoped>
  .budget_content {
    margin: 20px;
    font-family: '庞门正道真贵楷体';
  }
  .budget_card {
    background-color: #F9C3C2;
    padding: 30px;
    border-radius: 6px;
    color: white;
  }
  .card_surplus {
    text-align: left;
    display: flex;
    align-items: center;
  }
  .card_surplus .card_text {
    margin-left: 20px;
  }
  .card_number {
    font-size: 30px;
  }
  .card_compute {
    display: flex;
    justify-content: space-between;
    margin-top: 30px;
  }
  .card_compute .card_number {
    font-size: 24px;
  }
  .budget_input {
    margin: 20px;
  }
  .input_header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  .budget_input .input {
    text-align: left;
    position: relative;
    height: 30px;
    line-height: 30px;
  }
  .budget_input .input input {
    border: none;
  }
  .budget_input .delete {
    position: absolute;
    right: 0;
    line-height: 30px;
    height: 30px;
  }
  .show_month {
    position: relative;
  }
  .select_month {
    position: absolute;
    top: 50px;
    right: 8px;
    box-shadow: #ccc 2px 2px 6px;
    width: 34%;
  }
</style>